using Godot;
using System;

namespace Box;

public partial class TaskSelectPropertyControl : HBoxContainer,IProperty
{

	public object PValue {get;set;}

	public string PName {get;set;}

	static ItemSelectWindow FileSelectWindow {
		get {
			if(file_select_window == null) {
				file_select_window = GD.Load<PackedScene>("res://source/process_tree_editor/item_select_window/ItemSelectWindow.tscn").Instantiate<ItemSelectWindow>();
			}
			return file_select_window;
		}
	}
	static ItemSelectWindow file_select_window;
	static ItemSelectTree ItemSelectTree;

	Button OpenFileSelectButton;
	Label label;

	public bool selecting = false;

	public bool is_connect_on_confirm = false;

	public override void _Ready()
	{
		OpenFileSelectButton = GetNode<Button>("Input");
		OpenFileSelectButton.ButtonDown += _onOpenFileSelectWindow;
		label = GetNode<Label>("Label");
		label.Text = PName;

		if(PValue != null) {
			OpenFileSelectButton.Text = (string)PValue;
		}
	}

	public override string ToString() {
		return PValue.ToString();
	}

	public void _onOpenFileSelectWindow() {
		if(!FileSelectWindow.IsInsideTree()) {
			GetTree().CurrentScene.AddChild(FileSelectWindow);
		}
		if(ItemSelectTree == null) {
			ItemSelectTree = FileSelectWindow.ItemSelectControl.ItemSelectTree;
			ItemSelectTree.FilterType ="task";
			is_connect_on_confirm = true;
			FileSelectWindow.ItemSelectControl.onConfirm += _onConfirm;
		} else {
			if(!is_connect_on_confirm) {
				is_connect_on_confirm = true;
				FileSelectWindow.ItemSelectControl.onConfirm += _onConfirm;
			}
			ItemSelectTree.UpdateSelectTree();
		}
		selecting = true;
		FileSelectWindow.Show();
	}

	public void _onConfirm(string class_name) {
		if(selecting) {
			selecting = false;
			PValue = class_name;
			OpenFileSelectButton.Text = class_name;
		}

		FileSelectWindow.Hide();
	}
}
